import React, { useEffect, useMemo, useRef, useState } from "react";
import { getHttp, postHttp } from "../../../api";
import { useAppSelector } from "../../../store/hooks";
import { useRequest } from "ahooks";
import style from "./style.module.scss";
import { MyNavBar } from "../../../components";
import doctorIcon from "../../../assets/images/image/hdpi/historical_inquiry.png";
// import doctorIcon from '../../../assets/images/image/hdpi/'
import userIcon from "../../../assets/images/image/hdpi/boy.png";
import voiceIcon from "../../../assets/images/icon/hdpi/common_icon_voice_n.png";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Button, Dialog, Notify } from "react-vant";
import { dateYearToDate } from "../../../utils/formatTime";
import io from "socket.io-client";
import { contentToEmoji } from "../../../utils/emojiList";
import { Image } from 'antd'
const socket = io("http://127.0.0.1:8000");
interface FormParam {
  inquiryId: string;
  content: string;
  type: string;
  userId: string;
}

interface ChatState {
  askTime: number;
  content: string;
  direction: number;
  doctorHeadPic: string;
  msgType: number;
  userHeadPic: string;
  fail: false;
}

interface failList {
  askTime: number;
  fail: true;
  msgType: number;
  direction: number;
  inquiryId: string;
  content: string;
  type: string;
  userId: string;
}

type ListState = ChatState | failList;


function renderContent(content: string) {
  content = content.trim()
  try {
    if(content.startsWith('{') && content.endsWith('}')) {
      const v = JSON.parse(content);

      if(v.type.includes('image')) {
        return <Image src={v.url} alt="" width={100}></Image>
      }

      if(v.type.includes('video')) {
        return <video  src={v.url}  width={100} controls></video>
      }
      return '该文件目前不支持'
    } else {
      return contentToEmoji(content)
    }
  } catch {
    return contentToEmoji(content)
  }
}


const Index: React.FC = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const nickName = searchParams.get("nickName") as string;
  const userId = searchParams.get("userId") as string;
  const recordId = searchParams.get("recordId") as string;
  const type = searchParams.get("type") as string;
  const imagePic = useAppSelector((state) => state.user.doctor.imagePic);
  const contentRef = useRef<HTMLDivElement | null>(null);

  // 获取聊天数据
  const [chatList, setChatList] = useState<ListState[]>([]);
  // 获取本地发送失败数据
  const failKey = `${userId}${recordId}`;
  const [failList, setFailList] = useState<ListState[]>(() => {
    const result = localStorage.getItem(failKey);
    if (result) {
      return JSON.parse(result);
    } else {
      return [];
    }
  });
  // 渲染数据
  const list = useMemo(() => {
    console.log(chatList, "chat");
    return chatList.concat(failList).sort((a, b) => {
      return a.askTime - b.askTime;
    });
  }, [chatList, failList]);

  // 获取聊天记录 参数
  const [historyParams, setHistoryParams] = useState({
    // 问诊记录id
    recordId: recordId,
    page: 1,
    count: 20,
  });
  // 发送消息 参数
  const [putContent, setPutContent] = useState<FormParam>({
    // 问诊id
    inquiryId: recordId,
    content: "",
    type: "1",
    // 用户id
    userId: userId,
  });

  // 发送消息
  const onSend = async (putContent: FormParam) => {
    // 没网处理
    if (!globalThis.navigator.onLine) {
      const failData: failList = {
        ...putContent,
        askTime: new Date().getTime(),
        fail: true,
        msgType: 1,
        direction: 1,
      };

      setFailList([...failList, failData]);
      return;
    }
    const resp = await postHttp(
      "/health/doctor/inquiry/verify/v1/pushMessage",
      putContent,
      { "Content-Type": "application/x-www-form-urlencoded" }
    );
    if (resp.status === "0000") {
      socket.emit("update");
    }
    return resp;
  };

  const putFaillMessage = async (v: ListState) => {
    if (!globalThis.navigator.onLine) {
      Notify.show({ type: "danger", message: "当前没有可用网络" });
      return;
    }
    Dialog.confirm({
      message: "确定要重新发送消息吗",
    })
      .then(async () => {
        const resp = await onSend({
          inquiryId: recordId,
          content: v.content,
          type: "1",
          userId: userId,
        });

        if (resp?.status === "0000") {
          const result = failList.filter((item) => item.askTime !== v.askTime);
          setFailList(result);
        }
      })
      .catch(() => ({}));
  };
  //  获取聊天记录 函数
  const queryHistoryMessage = async () => {
    const resp = await getHttp(
      "/health/doctor/inquiry/verify/v1/findInquiryDetailsList",
      historyParams
    );

    setChatList(resp.result || []);
  };

  useEffect(() => {
    queryHistoryMessage();

    socket.on("update", (data: any) => {
      queryHistoryMessage();
    });
  }, []);

  useEffect(() => {
    if (contentRef.current) {
      contentRef.current.scrollTop = contentRef.current.scrollHeight;
    }
  }, [list]);

  useEffect(() => {
    localStorage.setItem(failKey, JSON.stringify(failList));
  }, [failList]);
  const m5 = 1000 * 60 * 5;
  return (
    <div className={style.chat}>
      <div className={style.navbar}>
        <MyNavBar
          title={nickName}
          leftArrow
          onClickLeft={() => navigate(-1)}
          style={{ backgroundColor: "#fff" }}
        ></MyNavBar>
      </div>
      <div className={style.content} ref={contentRef}>
        {list.map((v, i) => {
          return (
            <div key={i}>
             {i === 0 ? (
                <div className={style.currentTime}>
                  {dateYearToDate(new Date(v.askTime)).yearToDate}
                  {dateYearToDate(new Date(v.askTime)).time}
                </div>
              ) : v.askTime - list[i - 1].askTime > m5 ? (
                <div className={style.currentTime}>
                  {dateYearToDate(new Date(v.askTime)).yearToDate}
                  {dateYearToDate(new Date(v.askTime)).time}
                </div>
              ) : (
                ""
              )}
              {/* 失败 */}
              {v.fail && (
                <div className={style.userMessage_wrapper}>
                  <Button
                    type="danger"
                    size="mini"
                    style={{ marginRight: 10 }}
                    onClick={() => putFaillMessage(v)}
                  >
                    !
                  </Button>
                  <div
                    className={style.userMessage}
                    onClick={queryHistoryMessage}
                  >
                    {renderContent(v.content)}
                  </div>
                  <img src={imagePic} alt="" className={style.userIcon} />
                </div>
              )}
              {/* 成功 */}
              {!v.fail && (
                <div>
                  {v.direction === 2 && (
                    <div className={style.doctorMessage_wrapper}>
                      <img
                        src={v.userHeadPic}
                        alt=""
                        className={style.doctorIcon}
                      />
                      <div className={style.doctorMessage}>{renderContent(v.content)}</div>
                    </div>
                  )}
                  {v.direction === 1 && (
                    <div className={style.userMessage_wrapper}>
                      <div
                        className={style.userMessage}
                        // onClick={queryHistoryMessage}
                      >
                        {renderContent(v.content)}
                      </div>
                      <img
                        src={imagePic}
                        alt=""
                        className={style.userIcon}
                        onError={(e) =>
                          ((e.target as HTMLImageElement).src = imagePic)
                        }
                      />
                    </div>
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>
      {
        type !== '2' && <div className={style.footer}>
        <img src={voiceIcon} alt="" className={style.voiceIcon} />
        <input
          type="text"
          value={putContent.content}
          onChange={(e) =>
            setPutContent({
              ...putContent,
              content: e.target.value,
            })
          }
          className={style.input}
        />
        <button className={style.btn_send} onClick={() => onSend(putContent)}>
          确定
        </button>
      </div>
      }
    </div>
  );
};

export default Index;
